<template>
  <div class="">
    <div class="mb-10px">
      <label>应用:</label>
      <Select
        v-model:value="appId"
        @select="getTenants"
        :options="appOptions.map((app) => ({ value: app.id, label: app.name }))"
        style="width: 200px; margin-left: 10px"
      >
      </Select>
      <label style="margin-left: 10px">租户:</label>
      <Select
        v-model:value="tenantId"
        :options="tenantsOptions.map((tenant) => ({ value: tenant.id, label: tenant.name }))"
        style="width: 200px; margin-left: 10px"
      >
      </Select>
      <InputSearch
        class="search_right w-250px"
        v-model:value="versionName"
        placeholder="请输入版本号"
        enter-button
        @search="onSearch"
        style="margin-left: 10px"
      ></InputSearch>
      <Button v-per="'upload'" style="float: right" @click="uploadScript" type="primary">上传脚本</Button>
    </div>
    <Table
      bordered
      class="main-table"
      :dataSource="upgradeList"
      :columns="columns"
      :pagination="false"
      :loading="loading"
      :scroll="scroll"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'state'">
          <span> {{ getStatus(record.state) }} </span>
        </template>
      </template>
      <template #action="{ record }">
        <span v-per="'detail'">
          <a @click="downloadSql(record)">查看</a>
        </span>
        <Divider type="vertical" />
        <span v-per="'execute'">
          <a @click="execute(record, 1)" v-if="record.state !== 2 && record.state !== 8"
            >执行<Divider type="vertical"
          /></a>
        </span>
        <span v-per="'rollBack'">
          <a @click="execute(record, 2)" v-if="record.state === 2 && record.fileRollback !== ''"
            >回滚<Divider type="vertical"
          /></a>
        </span>
        <span v-per="'delete'">
          <a @click="handleDelete(record)" v-if="record.state !== 2 && record.state !== 3">删除</a>
        </span>
      </template>
    </Table>
    <br />
    <Pagination
      :show-total="(total) => `共 ${page.total} 条`"
      v-model:current="page.current"
      :page-size-options="page.pageSizeOptions"
      :total="page.total"
      show-size-changer
      :page-size="page.pageSize"
      @showSizeChange="onShowSizeChange"
      @change="changeCurrent"
    >
    </Pagination>
    <SqlDetail :detailVisible="showFile" :record="recordData" @cancelDetail="handleCancel" />
  </div>
</template>

<script setup lang="ts">
import { defineProps, watch, ref } from 'vue';
import { Table, message, Divider, Pagination, InputSearch, Button, Select } from 'ant-design-vue';
import { columns, Page } from './record.data';
import SqlDetail from '../SqlDetail.vue';
import { getAppForTenants, getTenantListByApp } from '/@/api/upgrade-center/upgradeForm';
import { excecuteSql, getTaskList, deleteUpgradeRecord } from '/@/api/upgrade-center/datastore/upgradeDb';
import { ExcecuteRecord } from '/@/api/upgrade-center/model/upgradeDbModel';
import { AppItem, TenantItem } from '/@/api/upgrade-center/model/upgradeFormModel';
const scroll = ref<undefined | object>(undefined);
const loading = ref(false);

// 接收父组件的值
let props = defineProps({
  dbInfo: Object,
});
const appId = ref<string>('');
const tenantId = ref<string>('');
const emits = defineEmits(['uploadScript']);
const page = ref<Page>({
  current: 1,
  pageSizeOptions: ['10', '20', '30', '40', '50'],
  total: 0,
  pageSize: 10,
});
const versionName = ref('');
const upgradeList = ref<ExcecuteRecord[]>([]);
let showFile = ref(false);
const recordData = ref('');
async function reload() {
  let params = {
    version: versionName.value,
    current: page.value.current,
    size: page.value.pageSize,
    appId: appId.value,
    tenantId: tenantId.value,
  };
  loading.value = true;
  try {
    let res = await getTaskList(params);
    if (res) {
      page.value.total = res.total;
      upgradeList.value = res.items;
    }
  } finally {
    loading.value = false;
  }
}
const uploadScript = () => {
  emits('uploadScript', { appId: appId.value, tenantId: tenantId.value });
};
watch(props, (newValue) => {
  appId.value = newValue.dbInfo?.appId;
  tenantId.value = newValue.dbInfo?.tenantId;
  if (newValue.onload) {
    reload();
  }
});
function getStatus(status: number) {
  switch (status) {
    case 1:
      return '待执行';
    case 2:
      return '执行成功';
    case 3:
      return '回滚成功';
    case 8:
      return '回滚失败';
    case 9:
      return '升级失败';
  }
}
function onSearch() {
  reload();
}
const onShowSizeChange = (current: number, pageSize: number) => {
  page.value.current = 1;
  page.value.pageSize = pageSize;
  if (pageSize > 10) {
    scroll.value = { y: 500 };
  }
  reload();
};
const changeCurrent = (current: number) => {
  page.value.current = current;
  reload();
};
const downloadSql = (record) => {
  recordData.value = record;
  showFile.value = true;
};

async function handleDelete(record: Recordable) {
  try {
    const res = await deleteUpgradeRecord({ id: record.id });
    if (res) {
      message.success('删除记录成功');
    } else {
      message.error('删除记录失败');
    }
  } catch (e) {
    message.error('删除记录失败' + e);
  }
  reload();
}

async function execute(record: Recordable, type) {
  try {
    const params = {
      appId: record.appId,
      tenantId: record.tenantId,
      id: record.id,
      type,
    };
    const res = await excecuteSql(params);
    if (res === '执行迁移成功') {
      message.success('执行迁移成功');
    } else {
      message.error('执行迁移失败');
    }
  } catch (e) {
    message.error('执行迁移失败' + e);
  }
  reload();
}

const handleCancel = () => {
  showFile.value = false;
};

let appOptions = ref<AppItem[]>([]);
let tenantsOptions = ref<TenantItem[]>([]);

const getTenants = async () => {
  tenantsOptions.value = await getTenantListByApp({ appId: appId.value });
};
const getApp = async () => {
  appOptions.value = await getAppForTenants();
};
getApp();
watch([appId, tenantId], ([newAppId, newTenantId]) => {
  if (newAppId && newTenantId) {
    reload();
  }
});
defineExpose({ reload });
</script>
<style lang="less">
.ant-pagination {
  float: right;
}
</style>
